package com.sun.talk.utils

import com.google.zxing.*
import com.google.zxing.client.j2se.MatrixToImageWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import java.io.File
import java.util.HashMap
import com.google.zxing.client.j2se.BufferedImageLuminanceSource
import com.google.zxing.common.HybridBinarizer
import javax.imageio.ImageIO
import java.awt.image.BufferedImage


object QrCodeUtils {
    fun createQRCode(filePath:String , content:String ) {
		val width = 300    //图片的宽度
        val height = 300   //图片的高度
        val format = "png" //图片的格式
        /**
         * 定义二维码的参数
         */
        val hints = HashMap<EncodeHintType,Any>()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8"    //指定字符编码为“utf-8”
        hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.M  //指定二维码的纠错等级为中级
        hints[EncodeHintType.MARGIN] = 2    //设置图片的边距

        /**
         * 生成二维码
         */
        try {
            val bitMatrix = MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints)
            val file = File(filePath).toPath()
            MatrixToImageWriter.writeToPath(bitMatrix, format, file)
        } catch (e:Exception) {
            e.printStackTrace()
        }
	}

    fun getContentFromQRCode(filePath: String): String? {
        val formatReader = MultiFormatReader()
        val file = File(filePath)
        val image: BufferedImage
        return try {
            image = ImageIO.read(file)
            val binaryBitmap = BinaryBitmap(HybridBinarizer(BufferedImageLuminanceSource(image)))
            val hints = HashMap<DecodeHintType,Any>()
            hints[DecodeHintType.CHARACTER_SET] = "utf-8"    //指定字符编码为“utf-8”
            val result = formatReader.decode(binaryBitmap, hints)
            result.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }

    }
}